--[[ =========================================================================
   ROCKET POKER -- poker video de bar, pour CC:Tweaked
   -------------------------------------------------------------------------
   A installer sur un ADVANCED COMPUTER avec :
     - un MONITEUR AVANCE tactile (5x3 blocs conseille, ~74x28)
     - un Wired Modem
     - client_solde.lua et login_term.lua sur le meme computer

   Jeu de 53 cartes (52 + un JOKER wild). Cinq cartes, tu gardes ce que
   tu veux en touchant les cartes, un seul tirage. Ca paie a partir de
   la paire de valets.

   Sur un gain, la machine propose le QUITTE OU DOUBLE, sans limite de
   relances : elle retourne une carte, tu en choisis une parmi quatre.
   Plus forte, ton gain double. Plus faible, tu perds tout. Egalite, on
   rejoue sans rien perdre.

   BAREME : mesure, pas recopie. 400 000 mains simulees avec une
   strategie de joueur realiste, puis verifie sur trois tirages
   independants : 97,1 %, 97,5 %, 97,5 %. Un joueur parfait tirerait
   un peu plus, un joueur distrait un peu moins.

   LE QUITTE OU DOUBLE EST EQUITABLE : a egalite on rejoue, donc les
   chances sont exactement 50/50 et l'esperance vaut 1. Il ne change
   pas le RTP, il ne fait qu'augmenter la variance. C'est pour ca qu'un
   PLAFOND DE MACHINE est indispensable (CFG.maxWin) : sans lui, une
   serie chanceuse peut vider la banque.
========================================================================= ]]

--------------------------------------------------------------------------
-- CONFIGURATION
--------------------------------------------------------------------------
local CFG = {
  betLevels = { 10, 25, 50, 100, 250 },
  maxWin    = 50000,        -- plafond machine sur le quitte ou double
  fps       = 15,
  monitorName = nil,
}

-- categories : 1 rien, 2 paire J+, 3 deux paires, 4 brelan, 5 quinte,
-- 6 couleur, 7 full, 8 carre, 9 quinte flush, 10 cinq identiques,
-- 11 royale avec joker, 12 royale naturelle
local PAYS = { 0, 1, 1, 2, 3, 5, 6, 14, 50, 100, 100, 500 }
local NAMES = {
  "RIEN", "PAIRE DE VALETS OU MIEUX", "DEUX PAIRES", "BRELAN", "QUINTE",
  "COULEUR", "FULL", "CARRE", "QUINTE FLUSH", "CINQ IDENTIQUES",
  "ROYALE AVEC JOKER", "QUINTE ROYALE",
}
local SHORT = {
  "RIEN", "PAIRE J+", "2 PAIRES", "BRELAN", "QUINTE", "COULEUR", "FULL",
  "CARRE", "Q.FLUSH", "5 IDENT.", "ROYALE J", "ROYALE",
}

--------------------------------------------------------------------------
-- PERIPHERIQUES
--------------------------------------------------------------------------
local bank  = dofile("client_solde.lua")
local login = dofile("login_term.lua")

local mon
if CFG.monitorName then mon = peripheral.wrap(CFG.monitorName)
else mon = peripheral.find("monitor") end
if not mon then error("Aucun moniteur trouve (il doit etre avance).", 0) end

local speaker = peripheral.find("speaker")
local function beep(p, inst)
  if speaker then pcall(speaker.playNote, inst or "bit", 1, p or 12) end
end

--------------------------------------------------------------------------
-- PALETTE ET FRAMEBUFFER
--------------------------------------------------------------------------
local PAL = {
  ["0"] = 0xffffff, ["1"] = 0xff7a18, ["2"] = 0xff2f8f, ["3"] = 0xc3c7d4,
  ["4"] = 0xffd23f, ["5"] = 0x9dff5c, ["6"] = 0xff5fb0, ["7"] = 0x14141c,
  ["8"] = 0x3c3c4a, ["9"] = 0x0e5c2a, ["a"] = 0x8b5cd6, ["b"] = 0x1b3a8f,
  ["c"] = 0x7a0f16, ["d"] = 0x2fa84f, ["e"] = 0xd11f2a, ["f"] = 0x000000,
}

mon.setTextScale(0.5)
for hex, rgb in pairs(PAL) do
  pcall(mon.setPaletteColour, 2 ^ tonumber(hex, 16), rgb)
end

local W, H = mon.getSize()
local ct, cf, cb = {}, {}, {}

local function fbInit()
  W, H = mon.getSize()
  ct, cf, cb = {}, {}, {}
  for y = 1, H do ct[y], cf[y], cb[y] = {}, {}, {} end
end

local function clear(bg)
  bg = bg or "f"
  for y = 1, H do
    for x = 1, W do ct[y][x], cf[y][x], cb[y][x] = " ", "f", bg end
  end
end

local function px(x, y, bg)
  x, y = math.floor(x), math.floor(y)
  if x >= 1 and x <= W and y >= 1 and y <= H then
    ct[y][x], cf[y][x], cb[y][x] = " ", "f", bg
  end
end

local function rect(x1, y1, x2, y2, bg)
  for y = math.floor(y1), math.floor(y2) do
    for x = math.floor(x1), math.floor(x2) do px(x, y, bg) end
  end
end

local function text(x, y, s, fg, bg)
  x, y = math.floor(x), math.floor(y)
  for i = 1, #s do
    local xx = x + i - 1
    if xx >= 1 and xx <= W and y >= 1 and y <= H then
      ct[y][xx] = s:sub(i, i)
      cf[y][xx] = fg or "0"
      if bg then cb[y][xx] = bg end
    end
  end
end

local function center(x1, x2, y, s, fg, bg)
  text(math.floor(x1 + ((x2 - x1 + 1) - #s) / 2), y, s, fg, bg)
end

local function push()
  for y = 1, H do
    mon.setCursorPos(1, y)
    mon.blit(table.concat(ct[y]), table.concat(cf[y]), table.concat(cb[y]))
  end
end

fbInit()

--------------------------------------------------------------------------
-- FONTE 5x7
--------------------------------------------------------------------------
local FONT = {
  R="11110/10001/10001/11110/10100/10010/10001",
  O="01110/10001/10001/10001/10001/10001/01110",
  C="01110/10001/10000/10000/10000/10001/01110",
  K="10001/10010/10100/11000/10100/10010/10001",
  E="11111/10000/10000/11110/10000/10000/11111",
  T="11111/00100/00100/00100/00100/00100/00100",
  P="11110/10001/10001/11110/10000/10000/10000",
  A="01110/10001/10001/11111/10001/10001/10001",
  G="01110/10001/10000/10111/10001/10001/01111",
  D="11110/10001/10001/10001/10001/10001/11110",
  N="10001/11001/10101/10011/10001/10001/10001",
  I="11111/00100/00100/00100/00100/00100/11111",
  S="01111/10000/10000/01110/00001/00001/11110",
  U="10001/10001/10001/10001/10001/10001/01110",
  B="11110/10001/10001/11110/10001/10001/11110",
  L="10000/10000/10000/10000/10000/10000/11111",
  V="10001/10001/10001/10001/10001/01010/00100",
  X="10001/10001/01010/00100/01010/10001/10001",
  ["!"]="00100/00100/00100/00100/00100/00000/00100",
  ["+"]="00000/00100/00100/11111/00100/00100/00000",
  ["0"]="01110/10011/10101/10101/11001/10001/01110",
  ["1"]="00100/01100/00100/00100/00100/00100/01110",
  ["2"]="01110/10001/00001/00110/01000/10000/11111",
  ["3"]="11111/00010/00100/00010/00001/10001/01110",
  ["4"]="00010/00110/01010/10010/11111/00010/00010",
  ["5"]="11111/10000/11110/00001/00001/10001/01110",
  ["6"]="00110/01000/10000/11110/10001/10001/01110",
  ["7"]="11111/00001/00010/00100/01000/01000/01000",
  ["8"]="01110/10001/10001/01110/10001/10001/01110",
  ["9"]="01110/10001/10001/01111/00001/00010/01100",
  [" "]="00000/00000/00000/00000/00000/00000/00000",
}
local GLYPH = {}
for ch, def in pairs(FONT) do
  local rows = {}
  for r in def:gmatch("[^/]+") do rows[#rows + 1] = r end
  GLYPH[ch] = rows
end
local function bigWidth(s, sx) sx = sx or 1; return #s * (5 * sx + sx) - sx end
local function bigText(x0, y0, s, colFn, sx, sy)
  sx, sy = sx or 1, sy or 1
  local cx = x0
  for i = 1, #s do
    local g = GLYPH[s:sub(i, i)] or GLYPH[" "]
    for ry = 1, 7 do
      for rx = 1, 5 do
        if g[ry]:sub(rx, rx) == "1" then
          for iy = 0, sy - 1 do
            for ix = 0, sx - 1 do
              px(cx + (rx - 1) * sx + ix, y0 + (ry - 1) * sy + iy,
                 colFn(cx + (rx - 1) * sx + ix, ry))
            end
          end
        end
      end
    end
    cx = cx + 5 * sx + sx
  end
end

--------------------------------------------------------------------------
-- CARTES
--------------------------------------------------------------------------
-- carte 0..51 : rang = c % 13 (0 = 2, 12 = As), famille = c // 13
-- carte 52 : le JOKER
local JOKER = 52
local RANKTXT = { "2","3","4","5","6","7","8","9","10","J","Q","K","A" }
-- familles Team Rocket : Poke, Super, Hyper, Master Ball
local SUITCOL = { "e", "b", "4", "a" }

local function rankOf(c) return c % 13 end
local function suitOf(c) return math.floor(c / 13) end

local function newDeck()
  local d = {}
  for i = 0, 52 do d[#d + 1] = i end
  for i = #d, 2, -1 do
    local j = math.random(i)
    d[i], d[j] = d[j], d[i]
  end
  return d
end

--------------------------------------------------------------------------
-- EVALUATION DE LA MAIN (joker wild)
--------------------------------------------------------------------------
local function categoryOf(cards)
  local jok, real = 0, {}
  for _, c in ipairs(cards) do
    if c == JOKER then jok = jok + 1 else real[#real + 1] = c end
  end

  local function plain(cs, natural)
    local counts, suits = {}, {}
    local rs = {}
    for _, c in ipairs(cs) do
      local r = rankOf(c)
      counts[r] = (counts[r] or 0) + 1
      suits[suitOf(c)] = (suits[suitOf(c)] or 0) + 1
      rs[#rs + 1] = r
    end
    table.sort(rs)
    local best1, best2 = 0, 0
    for _, n in pairs(counts) do
      if n > best1 then best2 = best1; best1 = n
      elseif n > best2 then best2 = n end
    end
    local flush = false
    for _, n in pairs(suits) do if n == 5 then flush = true end end
    -- quinte
    local uniq = {}
    for _, r in ipairs(rs) do
      if uniq[#uniq] ~= r then uniq[#uniq + 1] = r end
    end
    local straight, high = false, nil
    if #uniq == 5 then
      if uniq[5] - uniq[1] == 4 then straight, high = true, uniq[5]
      elseif uniq[1] == 0 and uniq[2] == 1 and uniq[3] == 2
             and uniq[4] == 3 and uniq[5] == 12 then
        straight, high = true, 3
      end
    end
    if best1 == 5 then return 10 end
    if straight and flush then
      if high == 12 then return natural and 12 or 11 end
      return 9
    end
    if best1 == 4 then return 8 end
    if best1 == 3 and best2 == 2 then return 7 end
    if flush then return 6 end
    if straight then return 5 end
    if best1 == 3 then return 4 end
    if best1 == 2 and best2 == 2 then return 3 end
    if best1 == 2 then
      for r, n in pairs(counts) do
        if n == 2 then return (r >= 9) and 2 or 1 end
      end
    end
    return 1
  end

  if jok == 0 then return plain(real, true) end

  -- le joker prend la valeur qui arrange le plus
  local used = {}
  for _, c in ipairs(real) do used[c] = true end
  local best = 1
  for c = 0, 51 do
    if not used[c] then
      local t = {}
      for _, v in ipairs(real) do t[#t + 1] = v end
      t[#t + 1] = c
      local cat = plain(t, false)
      if cat > best then best = cat end
      if best >= 11 then break end
    end
  end
  return best
end

--------------------------------------------------------------------------
-- MISE EN PAGE
--------------------------------------------------------------------------
local L = {}
local function layout()
  fbInit()
  L.x1, L.y1, L.x2, L.y2 = 2, 2, W - 1, H - 1
  L.payW = (W >= 66) and 22 or 0
  L.payX = L.payW > 0 and (L.x2 - L.payW + 1) or nil
  L.tableX2 = L.payW > 0 and (L.payX - 2) or L.x2

  L.cardW = math.max(7, math.min(11, math.floor((L.tableX2 - L.x1 - 6) / 5)))
  -- les cartes prennent toute la hauteur disponible entre l'entete et
  -- la barre d'action : sinon la moitie basse de l'ecran reste vide
  L.cardH = math.max(6, math.min(13, (L.y2 - 3) - (L.y1 + 4) - 3))
  L.gap = math.max(1, math.floor((L.tableX2 - L.x1 + 1 - 5 * L.cardW) / 6))
  L.cardsY = L.y1 + 4
  L.cardsX = {}
  local total = 5 * L.cardW + 4 * L.gap
  local x0 = math.floor((L.x1 + L.tableX2) / 2 - total / 2)
  for i = 1, 5 do L.cardsX[i] = x0 + (i - 1) * (L.cardW + L.gap) end
  L.holdY = L.cardsY + L.cardH
  L.msgY = L.y2 - 1
end
layout()

--------------------------------------------------------------------------
-- DESSIN DES CARTES
--------------------------------------------------------------------------
local function drawCardBack(x, y)
  rect(x - 1, y - 1, x + L.cardW, y + L.cardH, "f")
  rect(x, y, x + L.cardW - 1, y + L.cardH - 1, "e")
  rect(x + 1, y + 1, x + L.cardW - 2, y + L.cardH - 2, "b")
  center(x, x + L.cardW - 1, y + math.floor(L.cardH / 2) - 1, "R", "4", "b")
end

local function drawCard(x, y, c, dim)
  rect(x - 1, y - 1, x + L.cardW, y + L.cardH, "f")
  rect(x, y, x + L.cardW - 1, y + L.cardH - 1, dim and "3" or "0")
  if c == JOKER then
    -- le joker : une Master Ball et le mot JOKER
    center(x, x + L.cardW - 1, y, "JOKER", "a", dim and "3" or "0")
    local bx = x + math.floor((L.cardW - 5) / 2)
    local by = y + math.floor((L.cardH - 3) / 2)
    rect(bx + 1, by, bx + 3, by, "a")
    px(bx, by + 1, "a"); px(bx + 4, by + 1, "a")
    px(bx + 1, by + 1, "f"); px(bx + 3, by + 1, "f")
    px(bx + 2, by + 1, "6")
    rect(bx + 1, by + 2, bx + 3, by + 2, "3")
    center(x, x + L.cardW - 1, y + L.cardH - 1, "WILD", "a", dim and "3" or "0")
    return
  end
  local rt = RANKTXT[rankOf(c) + 1]
  local col = SUITCOL[suitOf(c) + 1]
  text(x, y, rt, col, dim and "3" or "0")
  text(x + L.cardW - #rt, y + L.cardH - 1, rt, col, dim and "3" or "0")
  -- Poke Ball de la famille, au centre
  local bx = x + math.floor((L.cardW - 5) / 2)
  local by = y + math.floor((L.cardH - 3) / 2)
  rect(bx + 1, by, bx + 3, by, col)
  px(bx, by + 1, col); px(bx + 4, by + 1, col)
  px(bx + 1, by + 1, "f"); px(bx + 3, by + 1, "f")
  px(bx + 2, by + 1, "0")
  rect(bx + 1, by + 2, bx + 3, by + 2, "3")
end

local function drawHoldTag(i, held)
  local x = L.cardsX[i]
  rect(x - 1, L.holdY, x + L.cardW, L.holdY + 1, held and "5" or "8")
  center(x - 1, x + L.cardW, L.holdY, held and "GARDEE" or "toucher",
         held and "f" or "3", held and "5" or "8")
  center(x - 1, x + L.cardW, L.holdY + 1, held and "" or "pour garder",
         "3", held and "5" or "8")
end

--------------------------------------------------------------------------
-- BANDEAUX
--------------------------------------------------------------------------
local CHASE = { "4", "1", "e", "c" }
local function drawFrame(t, flash)
  local step = math.floor(t * 6)
  for x = 1, W do
    local a = flash and (((x + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((x + step) % 4) + 1]
    px(x, 1, a); px(x, H, a)
  end
  for y = 1, H do
    local a = flash and (((y + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((y + step) % 4) + 1]
    px(1, y, a); px(W, y, a)
  end
end

local function fmt(n)
  local s = tostring(math.floor(n))
  local out = ""
  while #s > 3 do out = " " .. s:sub(-3) .. out; s = s:sub(1, -4) end
  return s .. out
end

local function drawPaytable(bet, hilite)
  if L.payW == 0 then return end
  local x1, x2 = L.payX, L.x2
  rect(x1 - 1, L.y1, x2, L.y2, "f")
  rect(x1, L.y1, x2, L.y1, "e")
  center(x1, x2, L.y1, "TABLE DES GAINS", "4", "e")
  local y = L.y1 + 1
  for cat = 12, 2, -1 do
    if y > L.y2 - 1 then break end
    local on = (hilite == cat)
    if on then rect(x1, y, x2, y, "c") end
    text(x1, y, SHORT[cat], on and "4" or "3", on and "c" or nil)
    local v = PAYS[cat] * (bet or 1)
    local s = (bet and fmt(v) or ("x" .. PAYS[cat]))
    text(x2 - #s + 1, y, s, on and "0" or "5", on and "c" or nil)
    y = y + 1
  end
  if y <= L.y2 then
    text(x1, y + 1, "Joker = carte libre", "a")
  end
end

local function drawHeader(t, player, credit, bet, title)
  rect(L.x1, L.y1, L.tableX2, L.y1 + 2, "f")
  local s = title or "ROCKET POKER"
  local w = bigWidth(s)
  if w <= (L.tableX2 - L.x1) and L.y1 + 6 < L.cardsY then
    bigText(L.x1 + 1, L.y1, s, function(_, gy)
      return gy <= 3 and "4" or "e"
    end)
  else
    center(L.x1, L.tableX2, L.y1, s, "4")
  end
  if player then
    local r = player .. "  " .. fmt(credit or 0)
    text(L.tableX2 - #r + 1, L.y1, r, "3")
    if bet then
      local b = "MISE " .. fmt(bet)
      text(L.tableX2 - #b + 1, L.y1 + 1, b, "5")
    end
  end
end

--------------------------------------------------------------------------
-- ECRAN DE VEILLE
--------------------------------------------------------------------------
local STATE = { busy = false }

local ADS = {
  "Le joker remplace n'importe quelle carte.",
  "Ca paie des la paire de valets.",
  "Quitte ou double : autant de fois que tu oses.",
  "Quinte royale : 500 fois ta mise.",
}

local function attractFrame(t)
  clear("f")
  -- cinq cartes qui se retournent l'une apres l'autre
  local demo = { 9, 22, JOKER, 12, 35 }
  for i = 1, 5 do
    local phase = (t * 0.8 + i * 0.7) % 6
    if phase < 3 then drawCard(L.cardsX[i], L.cardsY, demo[i])
    else drawCardBack(L.cardsX[i], L.cardsY) end
  end
  drawHeader(t, nil, nil, nil, "ROCKET POKER")
  center(L.x1, L.tableX2, L.y1 + 3, "POKER VIDEO - 53 CARTES AVEC JOKER", "6")
  center(L.x1, L.tableX2, L.holdY + 1,
         ADS[(math.floor(t / 4) % #ADS) + 1], "3")
  center(L.x1, L.tableX2, L.msgY,
         "INSCRIS-TOI SUR LE TERMINAL POUR JOUER", "0")
  drawPaytable(nil, nil)
  drawFrame(t)
  push()
end

local function attractLoop()
  while true do
    if not STATE.busy then pcall(attractFrame, os.clock()) end
    sleep(1 / 8)
  end
end

--------------------------------------------------------------------------
-- LE TOUR DE JEU
--------------------------------------------------------------------------
local function render(player, credit, bet, hand, held, phase, msg, msgCol,
                      hilite, revealed)
  clear("f")
  drawHeader(os.clock(), player, credit, bet)
  for i = 1, 5 do
    if hand[i] then
      if revealed == false and not held[i] then
        drawCardBack(L.cardsX[i], L.cardsY)
      else
        drawCard(L.cardsX[i], L.cardsY, hand[i])
      end
    else
      drawCardBack(L.cardsX[i], L.cardsY)
    end
    if phase == "hold" then drawHoldTag(i, held[i]) end
  end
  drawPaytable(bet, hilite)
  if msg then
    rect(L.x1, L.msgY, L.tableX2, L.msgY, "f")
    center(L.x1, L.tableX2, L.msgY, msg, msgCol or "0")
  end
  drawFrame(os.clock(), hilite ~= nil and hilite >= 8)
  push()
end

local function cardAt(x, y)
  if y < L.cardsY - 1 or y > L.holdY + 1 then return nil end
  for i = 1, 5 do
    if x >= L.cardsX[i] - 1 and x <= L.cardsX[i] + L.cardW then return i end
  end
  return nil
end

-- Quitte ou double : une carte du croupier, quatre faces cachees.
-- A egalite on rejoue, donc le jeu est exactement equitable.
local function gamble(player, gain, bet)
  while true do
    local deck = newDeck()
    local dealer
    repeat dealer = table.remove(deck) until dealer ~= JOKER
    local choices = {}
    for i = 1, 4 do
      local c
      repeat c = table.remove(deck) until c ~= JOKER
      choices[i] = c
    end

    local picked, done = nil, false
    while not done do
      clear("f")
      drawHeader(os.clock(), player, nil, nil, "QUITTE OU DOUBLE")
      center(L.x1, L.tableX2, L.y1 + 3,
             "GAIN EN JEU : " .. fmt(gain) .. " CREDITS", "4")

      -- carte du croupier a gauche, les quatre choix a droite
      drawCard(L.cardsX[1], L.cardsY, dealer)
      center(L.cardsX[1] - 1, L.cardsX[1] + L.cardW, L.holdY,
             "CROUPIER", "e")
      for i = 1, 4 do
        local x = L.cardsX[i + 1]
        if picked == i then drawCard(x, L.cardsY, choices[i])
        else drawCardBack(x, L.cardsY) end
        center(x - 1, x + L.cardW, L.holdY, tostring(i), "4")
      end

      if not picked then
        center(L.x1, L.tableX2, L.msgY - 1,
               "TOUCHE UNE CARTE : PLUS FORTE, TU DOUBLES", "0")
        center(L.x1, L.tableX2, L.msgY,
               "TOUCHE LE CROUPIER POUR ENCAISSER " .. fmt(gain), "5")
      end
      drawFrame(os.clock())
      push()

      if picked then done = true break end
      local ev, side, mx, my = os.pullEvent("monitor_touch")
      local idx = cardAt(mx, my)
      if idx == 1 then
        return gain, "encaisse"
      elseif idx then
        picked = idx - 1
        beep(14)
      end
    end

    -- resultat
    local pc, dc = rankOf(choices[picked]), rankOf(dealer)
    local outcome
    if pc > dc then outcome = "gagne"
    elseif pc < dc then outcome = "perdu"
    else outcome = "egalite" end

    local newGain = gain
    if outcome == "gagne" then
      newGain = math.min(CFG.maxWin, gain * 2)
      beep(20, "bell")
    elseif outcome == "perdu" then
      newGain = 0
      beep(3, "bass")
    else
      beep(10)
    end

    local t0 = os.clock()
    while os.clock() - t0 < 3.2 do
      clear("f")
      drawHeader(os.clock(), player, nil, nil, "QUITTE OU DOUBLE")
      drawCard(L.cardsX[1], L.cardsY, dealer)
      center(L.cardsX[1] - 1, L.cardsX[1] + L.cardW, L.holdY, "CROUPIER", "e")
      for i = 1, 4 do
        local x = L.cardsX[i + 1]
        drawCard(x, L.cardsY, choices[i], i ~= picked)
      end
      local msg, col
      if outcome == "gagne" then
        msg = "GAGNE ! " .. fmt(gain) .. " DEVIENT " .. fmt(newGain)
        col = "5"
        if newGain >= CFG.maxWin then
          msg = "PLAFOND MACHINE ATTEINT : " .. fmt(newGain)
          col = "4"
        end
      elseif outcome == "perdu" then
        msg = "PERDU ! LA MACHINE RAMASSE " .. fmt(gain)
        col = "e"
      else
        msg = "EGALITE - ON REJOUE, TU NE PERDS RIEN"
        col = "4"
      end
      center(L.x1, L.tableX2, L.y1 + 3, msg, col)
      if outcome == "gagne" then
        for k = 1, 40 do
          local sx = L.x1 + ((k * 31 + math.floor(os.clock() * 17))
                     % (L.tableX2 - L.x1))
          local sy = L.cardsY + ((k * 7) % L.cardH)
          px(sx, sy, ({ "4", "0", "5" })[(k % 3) + 1])
        end
      end
      drawFrame(os.clock(), outcome == "gagne")
      push()
      sleep(1 / CFG.fps)
    end

    if outcome == "perdu" then return 0, "perdu" end
    if outcome == "gagne" then
      gain = newGain
      if gain >= CFG.maxWin then return gain, "plafond" end
    end
    -- egalite : on repart pour un tour, sans changer le gain
  end
end

local function playHand(player, bet, credit)
  STATE.busy = true
  local deck = newDeck()
  local hand, held = {}, {}
  for i = 1, 5 do hand[i] = table.remove(deck); held[i] = false end

  -- distribution, une carte apres l'autre
  for i = 1, 5 do
    local partial = {}
    for k = 1, i do partial[k] = hand[k] end
    render(player, credit, bet, partial, held, "deal",
           "DISTRIBUTION...", "3")
    beep(12)
    sleep(0.18)
  end

  -- phase de conservation
  local msg = "TOUCHE LES CARTES A GARDER, PUIS LE BAS DE L'ECRAN"
  while true do
    render(player, credit, bet, hand, held, "hold", msg, "0")
    local ev, side, mx, my = os.pullEvent("monitor_touch")
    local idx = cardAt(mx, my)
    if idx then
      held[idx] = not held[idx]
      beep(held[idx] and 14 or 8)
    elseif my >= L.msgY - 1 then
      break
    end
  end

  -- tirage
  for i = 1, 5 do
    if not held[i] then
      hand[i] = table.remove(deck)
      render(player, credit, bet, hand, held, "draw", "TIRAGE...", "4")
      beep(16)
      sleep(0.22)
    end
  end

  local cat = categoryOf(hand)
  local gain = PAYS[cat] * bet
  local msg2, col
  if gain > 0 then
    msg2 = NAMES[cat] .. "   +" .. fmt(gain)
    col = "5"
    beep(18, "bell")
  else
    msg2 = "RIEN CETTE FOIS"
    col = "e"
    beep(4)
  end
  local t0 = os.clock()
  while os.clock() - t0 < 2.5 do
    render(player, credit, bet, hand, held, "result", msg2, col, cat)
    sleep(1 / CFG.fps)
  end

  -- quitte ou double
  local mode = "simple"
  if gain > 0 then
    local t1 = os.clock()
    local want = nil
    while os.clock() - t1 < 8 and want == nil do
      clear("f")
      drawHeader(os.clock(), player, credit, bet)
      for i = 1, 5 do drawCard(L.cardsX[i], L.cardsY, hand[i]) end
      drawPaytable(bet, cat)
      center(L.x1, L.tableX2, L.holdY,
             NAMES[cat] .. "  ->  " .. fmt(gain), "5")
      rect(L.x1, L.msgY - 1, math.floor((L.x1 + L.tableX2) / 2) - 1,
           L.msgY, "d")
      center(L.x1, math.floor((L.x1 + L.tableX2) / 2) - 1, L.msgY - 1,
             "ENCAISSER", "f", "d")
      center(L.x1, math.floor((L.x1 + L.tableX2) / 2) - 1, L.msgY,
             fmt(gain), "f", "d")
      rect(math.floor((L.x1 + L.tableX2) / 2) + 1, L.msgY - 1,
           L.tableX2, L.msgY, "e")
      center(math.floor((L.x1 + L.tableX2) / 2) + 1, L.tableX2, L.msgY - 1,
             "QUITTE OU DOUBLE", "0", "e")
      center(math.floor((L.x1 + L.tableX2) / 2) + 1, L.tableX2, L.msgY,
             "tente le double", "0", "e")
      drawFrame(os.clock(), true)
      push()

      local timer = os.startTimer(0.2)
      local ev, p1, mx, my = os.pullEvent()
      if ev == "monitor_touch" then
        if my >= L.msgY - 1 then
          want = (mx <= math.floor((L.x1 + L.tableX2) / 2)) and "cash" or "double"
        end
      end
    end
    if want == "double" then
      gain, mode = gamble(player, gain, bet)
    end
  end

  STATE.busy = false
  return gain, cat, mode
end

--------------------------------------------------------------------------
-- TERMINAL
--------------------------------------------------------------------------
local TW, TH = term.getSize()

local function tFill(y, bg)
  term.setBackgroundColor(bg)
  term.setCursorPos(1, y)
  term.write(string.rep(" ", TW))
end

local function tLabel(x, y, s, fg, bg)
  term.setCursorPos(x, y)
  term.setTextColor(fg)
  term.setBackgroundColor(bg or colors.black)
  term.write(s)
end

local function tCenter(y, s, fg, bg)
  tLabel(math.floor((TW - #s) / 2) + 1, y, s, fg, bg)
end

local function splash()
  term.setBackgroundColor(colors.black)
  term.clear()
  tFill(1, colors.red)
  tCenter(1, "ROCKET POKER", colors.yellow, colors.red)
  tCenter(3, "Poker video - 53 cartes avec joker", colors.white)
  tCenter(5, "Ca paie des la paire de valets", colors.lightGray)
  tCenter(6, "Quinte royale : 500 fois la mise", colors.yellow)
  tCenter(8, "Quitte ou double sans limite", colors.orange)
  tCenter(9, "(plafond machine : " .. fmt(CFG.maxWin) .. ")", colors.gray)
  tCenter(TH - 2, "Une touche pour jouer", colors.yellow)
  while true do
    local ev = os.pullEvent()
    if ev == "key" or ev == "mouse_click" then return end
  end
end

local function lobby(player)
  local betIdx = 3
  local credit = bank.getBalance(player)
  local buttons

  local function draw(msg, col)
    buttons = {}
    term.setBackgroundColor(colors.black)
    term.clear()
    tFill(1, colors.red)
    tLabel(2, 1, "ROCKET POKER", colors.yellow, colors.red)
    local right = player .. "  " .. fmt(credit)
    tLabel(TW - #right, 1, right, colors.white, colors.red)

    tLabel(2, 4, "MISE", colors.lightGray)
    term.setBackgroundColor(colors.red)
    term.setCursorPos(8, 4); term.write(" - ")
    buttons[#buttons + 1] = { id = "bet-", x1 = 8, x2 = 10, y = 4 }
    term.setBackgroundColor(colors.green)
    term.setCursorPos(20, 4); term.write(" + ")
    buttons[#buttons + 1] = { id = "bet+", x1 = 20, x2 = 22, y = 4 }
    tLabel(13, 4, fmt(CFG.betLevels[betIdx]), colors.yellow)

    term.setBackgroundColor(colors.green)
    term.setCursorPos(2, 6); term.write(string.rep(" ", 22))
    tLabel(6, 6, "DISTRIBUER", colors.white, colors.green)
    buttons[#buttons + 1] = { id = "go", x1 = 2, x2 = 23, y = 6 }

    term.setBackgroundColor(colors.red)
    term.setCursorPos(TW - 11, 6); term.write(string.rep(" ", 10))
    tLabel(TW - 9, 6, "QUITTER", colors.white, colors.red)
    buttons[#buttons + 1] = { id = "quit", x1 = TW - 11, x2 = TW - 2, y = 6 }

    tCenter(8, "Tout se joue sur le moniteur", colors.lightGray)
    tCenter(9, "Touche les cartes a garder", colors.gray)
    tFill(TH, colors.gray)
    if msg then tCenter(TH, msg, col or colors.white, colors.gray) end
  end

  draw("Espace = distribuer, +/- = mise")
  while true do
    local ev, p1, p2, p3 = os.pullEvent()
    local action
    if ev == "mouse_click" then
      for _, b in ipairs(buttons) do
        if p3 == b.y and p2 >= b.x1 and p2 <= b.x2 then action = b.id end
      end
    elseif ev == "key" then
      if p1 == keys.q then action = "quit"
      elseif p1 == keys.space or p1 == keys.enter then action = "go"
      elseif p1 == keys.equals or p1 == keys.numPadAdd then action = "bet+"
      elseif p1 == keys.minus or p1 == keys.numPadSubtract then action = "bet-"
      end
    end

    if action == "quit" then return
    elseif action == "bet+" then
      betIdx = math.min(betIdx + 1, #CFG.betLevels); draw()
    elseif action == "bet-" then
      betIdx = math.max(betIdx - 1, 1); draw()
    elseif action == "go" then
      local bet = CFG.betLevels[betIdx]
      local newBal, err = bank.addBalance(player, -bet)
      if not newBal then
        draw(err or "Banque injoignable", colors.red)
      else
        credit = newBal
        term.setBackgroundColor(colors.black)
        term.clear()
        tCenter(math.floor(TH / 2) - 1, "REGARDE LE MONITEUR", colors.yellow)
        tCenter(math.floor(TH / 2) + 1,
                "Touche les cartes a garder", colors.white)
        local gain, cat, mode = playHand(player, bet, credit)
        if gain > 0 then
          local nb = bank.addBalance(player, gain)
          credit = nb or (credit + gain)
        end
        if gain > 0 then
          draw(NAMES[cat] .. "  ->  +" .. fmt(gain) ..
               (mode == "encaisse" and " (encaisse)" or ""), colors.lime)
        else
          draw(cat >= 2 and "Perdu au quitte ou double" or "Rien cette fois",
               colors.red)
        end
      end
    end
  end
end

--------------------------------------------------------------------------
-- PROGRAMME PRINCIPAL
--------------------------------------------------------------------------
math.randomseed((os.epoch and os.epoch("utc") or os.time()) % 2147483647)

print("=== Rocket Poker ===")
print("Moniteur : " .. W .. "x" .. H)
print("53 cartes avec joker, paiement des la paire de valets")
print("RTP mesure sur 400 000 mains simulees : environ 97,4 %")

local function mainLoop()
  while true do
    splash()
    local player = login.authenticate("Connexion Rocket Poker")
    if player then lobby(player) end
  end
end

local ok, err = pcall(function()
  parallel.waitForAny(mainLoop, attractLoop)
end)

term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
term.setCursorPos(1, 1)
mon.setBackgroundColour(colours.black)
mon.clear()
if not ok and err ~= "Terminated" then error(err, 0) end
print("Rocket Poker : arret.")